// 深拷贝
// JSON.parse(JSON.stringify(obj))
// 无法解决循环引用 和 Date ，function等类型

const typeArray = ['[object Map]','[object Date]','[object Set]','[object Error]', '[object RegExp]'];

function deepClone(obj, map = new WeakMap()){
    if(map.has(obj)){
        return map.get(obj);
    }
    let res = Object.create(null)
    let type = Object.prototype.toString.call(obj);

    if(type === '[object Object]'){
        map.set(obj,res)
        for(let key of  Reflect.ownKeys(obj)){
            res[key] = deepClone(key,map);
        }
    } else if(Array.isArray(type)){
        map.set(obj,res)
        obj.forEach((element,index) => {
            res = []
            res[index] = deepClone(element,map)
        });
    } else if(typeArray.includes(type)) {
        res = new obj.constructor(obj);
    } else{
        res = obj;
    };
    return res;
}

const target = {
    field1: 1,
    field2: undefined,
    field3: {
        child: 'child'
        
    },
    field4: [2, 3, 8]
};
 target.target=target
 target.field4.push(target.field4)

let cloneTarget =deepClone(target)
target.field4.push(9)
console.log(target);
console.log(cloneTarget);